const { connection } = require("../base/connect");
const { md5 } = require("../../utils/crypto");
const {
  getTimeStamp,
  getCurrentTime,
  getLastDay,
} = require("../third-party/manage/time");
const tianApiKey = "d334721cf6eba2d619a5855420ec352c"; //天行数据api key值（flying_dark_feather提供）
const mu_xiao_guo_url = "https://api.muxiaoguo.cn/api/epidemic"; //木小果数据api
const wang_yi_lately = "https://c.m.163.com/ug/api/wuhan/app/data/list-total"; //网易api
const xin_lang_provinces = `https://49.4.25.117/JKZX/yq_${getLastDay()}.json`;
const mu_xiao_guo_api_key = "fa5d78ca7d58445d";
const mu_xiao_guo_secret_key = "a8e1fbb802ec9a141c0dd9a432b65acd";
const mu_xiao_guo_api_id = "10000305";
const isTokenValidate = true;

let maintain_max = 0; //激活
let updateCount = 0;
//导入各种更新函数
const refreshDanger = require("../third-party/muxiaoguo/danger"); //刷新风险地区信息
const refreshNews = require("../third-party/muxiaoguo/news"); //刷新疫情新闻信息
const refreshProvinces = require("../third-party/muxiaoguo/provinces"); //刷新疫情省市信息
const refreshForeign = require("../third-party/tianxing/foreign"); //刷新国外疫情信息
const refreshLately = require("../third-party/wangyi/lately"); //刷新最近60天疫情信息
const refreshArea = require("../third-party/xinlang/area"); //刷新新浪微博数据（主要用于省市）

function updateDB(callback) {
  const time_stamp = getTimeStamp(); //确保时间戳更新
  const mu_xiao_guo_sign = md5(
    `api_id=${mu_xiao_guo_api_id}&secretKey=${mu_xiao_guo_secret_key}&time_stamp=${time_stamp}`
  );
  const mu_xiao_guo_validate =
    "&sign=" + mu_xiao_guo_sign + "&time_stamp=" + time_stamp + "&";
  const mu_xiao_guo_base =
    mu_xiao_guo_url +
    "?" +
    "api_key=" +
    mu_xiao_guo_api_key +
    "&" +
    (isTokenValidate ? mu_xiao_guo_validate : "");
  connection.then((database) => {
    //更新指定数据成功的回调函数
    let successCollection = new Array(); //收集刷新成功的集合
    let failCollection = new Array(); //收集刷新失败的集合
    function updateCallback(type, collectionName) {
      updateCount++;
      if (type == "success") {
        console.log(collectionName + " 集合更新成功！");
        successCollection.push(collectionName);
        //同时修改collection的更新日志信息
        database
          .collection("collection")
          .updateOne(
            { code: collectionName },
            { $set: { update_time: getCurrentTime() } }
          );
      } else {
        console.log(collectionName + " 集合更新失败！");
        failCollection.push(collectionName);
      }
      if (updateCount == maintain_max) {
        updateCount = 0; //保障下一次更新
        let backObj = new Object();
        if (!failCollection.length) {
          database.collection("status").deleteOne({});
          database.collection("status").insertOne({
            updateTime: getCurrentTime(),
            dev_version: "v5.0.6",
            pro_version: "v4.4.6",
          });
          backObj.code = 200;
          backObj.text = "刷新数据库成功！";
        } else {
          backObj.code = -1;
          backObj.text =
            "刷新数据库失败，失败集合：" + failCollection.join(",");
        }
        callback && callback(backObj);
      }
    }
    //查看当前的所有数据同步要求
    const centerCollection = database.collection("collection");
    centerCollection
      .find({ state: "1" }, { projection: { code: 1, _id: 0 } })
      .toArray()
      .then((res) => {
        let optionArray = new Array();
        for (let i = 0; i < res.length; i++) {
          optionArray.push(res[i].code);
        }
        maintain_max = optionArray.length;
        if (!maintain_max) {
          //全部数据都关闭
          let backObj = new Object();
          backObj.code = 200;
          backObj.text = "刷新数据库成功！";
          callback && callback(backObj);
          return;
        }
        if (optionArray.indexOf("danger") != -1) {
          refreshDanger(
            updateCallback,
            database,
            mu_xiao_guo_base + "type=epidemicRiskLevel"
          );
        }
        if (optionArray.indexOf("news") != -1) {
          refreshNews(
            updateCallback,
            database,
            mu_xiao_guo_base + "type=epidemicHotspot"
          );
        }
        if (optionArray.indexOf("provinces") != -1) {
          refreshProvinces(
            updateCallback,
            database,
            mu_xiao_guo_base + "type=epidemicInfectionData"
          );
        }
        if (optionArray.indexOf("foreign") != -1) {
          refreshForeign(
            updateCallback,
            database,
            `https://api.tianapi.com/ncovabroad/index?key=${tianApiKey}`
          );
        }
        if (optionArray.indexOf("lately") != -1) {
          refreshLately(updateCallback, database, wang_yi_lately);
        }
        // console.log("输出请求的url:", xin_lang_provinces);
        // if (optionArray.indexOf("area") != -1) {
        //   refreshArea(updateCallback, database, xin_lang_provinces);
        // }
      });
  });
}
module.exports = async (ctx) => {
  async function delay(time) {
    return new Promise((resolve, reject) => {
      function callback(res) {
        resolve(res);
      }
      setTimeout(() => {
        updateDB(callback);
      }, time);
    });
  }
  await delay(0).then(
    (value) => {
      ctx.body = JSON.stringify(value);
    },
    (reason) => {
      console.log("错误：", reason);
      throwError(ctx, -3, reason);
    }
  );
};
//奥里给，完事了！
